<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Document</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
        <script type="text/javascript">
            'use strict';
            function buttonState() {
                var
                    form = $('#test-form'),
                    langs = form.find('[name=lang]'),
                    selectAll = form.find('label.selectAll :checkbox'),
                    selectAllLabel = form.find('label.selectAll span.selectAll'),
                    deselectAllLabel = form.find('label.selectAll span.deselectAll'),
                    invertSelect = form.find('a.invertSelect');

                // 重置初始化状态:
                form.find('*').show().off();
                form.find(':checkbox').prop('checked', false).off();
                deselectAllLabel.hide();
                // 拦截form提交事件:
                form.off().submit(function (e) {
                    e.preventDefault();
                    alert(form.serialize());
                });


                // TODO:绑定事件
                function updateLabel() {
                  let allChecked = langs.filter(':checked').length === langs.length

                  selectAll.prop('checked', allChecked)
                  if (allChecked) {
                    selectAllLabel.hide()
                    deselectAllLabel.show() 
                  } else {
                    selectAllLabel.show()
                    deselectAllLabel.hide() 
                  }
                }

                selectAll.change(function(e) {
                  langs.prop('checked', $(this).is(':checked'))
                  updateLabel()
                })

                invertSelect.click(function(e) {
                  langs.click()
                })

                langs.change(() => updateLabel())
            }
        </script>
    </head>
    <body>
        <!-- HTML结构 -->
        <button type="button" onclick="buttonState()">运行</button>
        <form id="test-form" action="test">
            <legend>请选择想要学习的编程语言：</legend>
            <fieldset>
                <p><label class="selectAll"><input type="checkbox"> <span class="selectAll">全选</span><span class="deselectAll">全不选</span></label> <a href="#0" class="invertSelect">反选</a></p>
                <p><label><input type="checkbox" name="lang" value="javascript"> JavaScript</label></p>
                <p><label><input type="checkbox" name="lang" value="python"> Python</label></p>
                <p><label><input type="checkbox" name="lang" value="ruby"> Ruby</label></p>
                <p><label><input type="checkbox" name="lang" value="haskell"> Haskell</label></p>
                <p><label><input type="checkbox" name="lang" value="scheme"> Scheme</label></p>
                <p><button type="submit">Submit</button></p>
            </fieldset>
        </form>
    </body>
</html>